package ca.kooki.codesnippet.core;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class FileAccessorTest {

  
  @Before
  public void setUp() throws IOException
  {
    SystemDate.reset();
    new File("example.txt").createNewFile();
  }
  
  @After
  public void tearDown()
  {
    SystemDate.reset();
    new File("example.txt").delete();
    new File("example.txt.lock").delete();
  }
  
  @Test
  public void CreateLockFileOnOpen() throws IOException, InterruptedException {
  
    FileAccessor accessor = new FileAccessor("example.txt");
    boolean wasLocked = accessor.lock();
    
    Assert.assertEquals(true, wasLocked);
    Assert.assertEquals(true, new File("example.txt.lock").exists());
    
  }
  
  @Test
  public void CannotLockIfAlreadyLocked() throws IOException, InterruptedException {
    
    FileAccessor accessor = new FileAccessor("example.txt");
    boolean wasLocked = accessor.lock();
    Assert.assertEquals(true, wasLocked);

    boolean wasLockedAgain = accessor.lock();
    Assert.assertEquals(false, wasLockedAgain);
  } 

  @Test
  public void KillLockIfOlderThanOneMinute() throws ParseException, IOException, InterruptedException {
    
    SystemDate.setNowTo("Nov 4, 2003 8:14 PM");
    FileAccessor accessor = new FileAccessor("example.txt");
    boolean wasLocked = accessor.lock();
    Assert.assertEquals(true, wasLocked);

    SystemDate.setNowTo("Nov 4, 2003 8:16 PM");
    
    boolean wasLockedAgain = accessor.lock();
    Assert.assertEquals(true, wasLockedAgain);
  } 

  @Test
  public void UnlockDeletesTheLockFile() throws IOException, InterruptedException
  {
    FileAccessor accessor = new FileAccessor("example.txt");
    boolean wasLocked = accessor.lock();
    
    Assert.assertEquals(true, wasLocked);
    Assert.assertEquals(true, new File("example.txt.lock").exists());

    accessor.unlock();
    Assert.assertEquals(true, new File("example.txt").canRead());
    Assert.assertEquals(true, new File("example.txt").canWrite());
    Assert.assertEquals(false, new File("example.txt.lock").exists());

  }
  
}
